package cn.tsmchina.one.controller.user;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tsmchina.one.domain.category.Category;
import cn.tsmchina.one.domain.user.Customer;
import cn.tsmchina.one.service.category.CategoryService;
import cn.tsmchina.one.service.menu.MenuService;
import cn.tsmchina.one.service.user.CustomerService;
import cn.tsmchina.one.util.C;
import cn.tsmchina.one.util.JsonUtil;
import cn.tsmchina.one.util.MD5Util;
import cn.tsmchina.one.util.Return;


@Controller
public class CustomerController {
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private CategoryService categoryService;

	
	@RequestMapping(value="/loginValid",method=RequestMethod.POST)
	@ResponseBody
	public Object login(@ModelAttribute("customer")
		Customer customer,@RequestParam String kaptcha,HttpServletRequest request) {
		Map<String, Object> data = new HashMap<>();
		Integer loginId = customer.getLoginId();
		String loginPwd = customer.getLoginPwd();
		
		String kaptchaExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if(!StringUtils.isEmpty(kaptchaExpected)){
			if(!kaptchaExpected.equals(kaptcha)){
				data.put("status", C.Msg.ERROR);
				data.put("msg", "验证码错误!");
				return data;
			}
		}
		
		if(null !=loginId){ 
			customer = customerService.getCustomerByLoginId(loginId);
			if(null != customer){
				String pwd = customer.getLoginPwd();
				//MD5码加密
				if(MD5Util.validatePassword(pwd, loginPwd)){
					//通过验证，登录成功
					request.getSession().setAttribute("customer", customer);
					request.getSession().setAttribute("menus", JsonUtil.parseJson(menuService.getAllMenu()));
					
					data.put("status", C.Msg.OK);
					data.put("msg", "登录成功!");
					return data;
				}
			}
		}
		
		data.put("status", C.Msg.ERROR);
		data.put("msg", "用户名或密码错误!");
		return data;
	}
	
	@RequestMapping("/login")
	public String login(){
		return "login";
	}
	
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,ModelMap model){
		request.getSession().removeAttribute("customer");
		return "redirect:login?cid="+request.getAttribute("loginId");
	}
	
	@RequestMapping("/updatePwd")
	public String updatePwd(String tLoginId,HttpServletRequest request,ModelMap model){
		//tLoginId = "1";
		request.setAttribute("tempLoginId", tLoginId);
		return "updatePwd";
	}
	
	@RequestMapping(value="/updatePwd",method=RequestMethod.POST)
	public String updatePassword(@RequestParam String oldPwd, @RequestParam String password,
			@RequestParam String confirmPwd,@RequestParam String loginId,HttpServletRequest request){
		
		request.setAttribute("msgType", C.Msg.ERROR);
		request.setAttribute("return",request.getContextPath()+"/updatePwd?loginId=loginId");
		
		if(StringUtils.isEmpty(oldPwd) || StringUtils.isEmpty(password)
				|| StringUtils.isEmpty(confirmPwd)){
			
			request.setAttribute("msg", "密码输入错误");
		}else{
			
			//Customer customer = (Customer) request.getSession().getAttribute("customer");
			Customer customer = customerService.getCustomerByLoginId(Integer.parseInt(loginId));
			Category category = categoryService.getByCategoryLoginId(Integer.parseInt(loginId));
			//密码输入是否正确
			if(!MD5Util.validatePassword(customer.getLoginPwd(), oldPwd)){
				request.setAttribute("msg", "原密码输入错误");
			}else{
				if(confirmPwd.equals(password)){
					String newPwd = MD5Util.encodeByMD5(confirmPwd);
					customer.setLoginPwd(newPwd);
					category.setLoginPwd(newPwd);
					customerService.updateCustomer(customer);
					categoryService.updateCategory(category);
					request.setAttribute("msgType", C.Msg.OK);
					request.setAttribute("msg", "修改成功");
					//request.removeAttribute("customer");
					
					request.setAttribute("return","categorym/query");
				}else{
					request.setAttribute("msg", "两次密码输入不一致");
				}
			}
		}
		
		//return Return.redirect(request);
		return "order/queryOrder";
	}
	
	@RequestMapping("/customer/queryCst")
	public String query(HttpServletRequest request,ModelMap model){
		List<Customer> customers = customerService.getAllCustomers();
		request.setAttribute("customers", customers);
		return "customer/queryCustomers";
	}
	
	@RequestMapping("/customer/add")
	public String add()
	{
		return "customer/addCustomer";
	}
	
	@RequestMapping(value="/customer/addCst", method = RequestMethod.POST)
	public String add(@ModelAttribute Customer customer, String password, HttpServletRequest request,ModelMap model){
		try
		{
			customer.setLoginPwd(MD5Util.encodeByMD5(password));
			customerService.addCustomer(customer);
			request.setAttribute("msgType", C.Msg.OK);
			request.setAttribute("msg", "添加成功!");
			request.setAttribute("return",request.getContextPath()+"/customer/queryCst");
		} catch (Exception e)
		{
			request.setAttribute("msgType", C.Msg.ERROR);
			request.setAttribute("msg", "添加失败!");
			request.setAttribute("return",request.getContextPath()+"/customer/queryCst");
		}
		return Return.redirect(request);
	}
	
	@RequestMapping("/customer/delCst/{id}")
	public String del(@PathVariable("id") long id, HttpServletRequest request,ModelMap model){
		
		try
		{
			customerService.deleteCustomer(id);
			request.setAttribute("msgType", C.Msg.OK);
			request.setAttribute("msg", "删除成功!");
			request.setAttribute("return",request.getContextPath()+"/customer/queryCst");
		} catch (Exception e)
		{
			request.setAttribute("msgType", C.Msg.ERROR);
			request.setAttribute("msg", "删除失败!");
			request.setAttribute("return",request.getContextPath()+"/customer/queryCst");
		}
		return Return.redirect(request);
		
	}
	
}
